<template>
  <div class="login">
    <van-nav-bar title="登录" />
    <van-form ref="loginFrom" @submit="login">
      <van-field
        placeholder="请输入手机号"
        name="mobile"
        v-model.trim="user.mobile"
        :rules="forRules.mobile"
      >
        <template #left-icon>
          <i class="toutiao toutiao-shouji"></i>
        </template>
      </van-field>
      <van-field
        placeholder="请输入验证码"
        v-model="user.code"
        :rules="forRules.code"
      >
        <i class="toutiao toutiao-yanzhengma" slot="left-icon"></i>
        <template #button>
           <van-count-down @finish='sending = false' :time="time" format="ss 秒" v-if="sending"/>
          <van-button
            v-else
            round
            size="small"
            type="default"
            @click="senCode"
            native-type="button"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn">
        <van-button block type="info" native-type="submit" :loading="loading" >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { sendSms,login } from "@/api/user.js";
export default {
  name:'login',
  data() {
    return {
      time: 6000,
      sending: false,
      loading: false,
      user: {
        mobile: "",
        code: "",
      },
      forRules: {
        mobile: [
          { required: true, message: "手机号不能为空" },
          { pattren: /^1\d{10}$/, massage: "手机号码不正确" },
        ],
        code: [
          {required: true, message: "验证码不能为空"},
          {pattren: /^\d{4,6}$/, massage: "验证码不正确"}
        ],
      },
    };
  },
  methods: {
    async senCode() {
      await this.$refs.loginFrom.validate("mobile");
      // console.log("验证成功");
        const res = await sendSms(this.user.mobile);
        this.$toast.success("短信验证发送成功");
        this.sending = true

    },
    async login(){
      try{
        this.loading = true
        const res = await login(this.user);
        this.$toast.success("登录成功");
        // console.log(res.data.data.token);
        this.$store.commit('setUser', res.data)
        this.$router.push('/my')
      }finally{
        this.loading = false
      }
    }
  },
};
</script>

<style scoped>
.login-btn {
  margin: 16px;
}
</style>